package com.yantong.controller;


import com.yantong.constant.PayStatus;
import com.yantong.mapper.TicketRecordUseMapper;
import com.yantong.mapper.TourNumberMapper;
import com.yantong.pojo.*;
import com.yantong.result.ResultVo;
import com.yantong.service.*;
import com.yantong.utils.PageUtils;
import com.yantong.utils.ValidateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;


/**
 * 观摩会管理
 */

@Controller
@RequestMapping("/localLife/manage")
public class LocalLifeController extends BaseController {
    private static final String prefix = "localLife";

    private Logger logger = LoggerFactory.getLogger(LocalLifeController.class);
    @Autowired
    private LocalLifeService localLifeService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private TicketService ticketService;
    @Autowired
    private TicketRecordUseMapper ticketRecordUseMapper;
    @Autowired
    private TourNumberService tourNumberService;
    @Autowired
    private CommanderListService commanderListService;
    @Autowired
    private TourNumberMapper tourNumberMapper;


    /**
     * 订单页面
     * @param model
     * @return
     */
    @RequiresPermissions("localLife:manage:orders")
    @GetMapping("/order")
    public String order(Model model) {
        model.addAttribute("payStatusList", PayStatus.getPayStatusList());
        model.addAllAttributes(getCentreIdModelInfo());
        return prefix + "/order";
    }

    /**
     * 订单列表数据
     */
    @ResponseBody
    @RequiresPermissions("localLife:manage:orders")
    @GetMapping("/list")
    public PageUtils<Order> list(ListOrderParams params, int offset, int limit) {
        Long teamId = getUserTeamId();
        if(null != teamId){
            params.setTmid(teamId);
        }
        return orderService.listOrders(params, offset, limit);
    }

    /**
     * 优惠券核销记录页面
     * @param model
     * @return
     */
    @RequiresPermissions("localLife:manage:tickets")
    @GetMapping("/ticket")
    public String ticket(Model model) {
        return prefix + "/ticket";
    }

    /**
     * 优惠券核销记录列表数据
     */
    @ResponseBody
    @RequiresPermissions("localLife:manage:tickets")
    @GetMapping("/ticketlist")
    public PageUtils<TicketRecordUse> ticketlist(String ticketType, Long centreId, String queryItem, Integer status, Long ticketId, Long judge, int offset, int limit) {
        return ticketService.listRecordUsers(ticketType,centreId, queryItem, status, ticketId, judge, offset, limit,getUserTeamId());
    }

    /**
     * 门店消费统计页面
     * @param model
     * @return
     */
    @RequiresPermissions("localLife:manage:statistics")
    @GetMapping("/statistics")
    public String statistics(Model model) {
        return prefix + "/statistics";
    }

    /**
     * 优惠券核销记录列表数据
     */
    @ResponseBody
    @RequiresPermissions("localLife:manage:statistics")
    @GetMapping("/statisticsList")
    public PageUtils<Statistics> statisticsList() {
        Long teamId = getUserTeamId();
        return localLifeService.statisticsList(teamId);
    }

    @ResponseBody
    @RequestMapping("/disableRecord")
    public ResultVo disableRecord(Long recordId) {
        TicketRecordUse record =  new TicketRecordUse();
        record.setId(recordId);
        record.setStatus(-1);
        if(ticketRecordUseMapper.updateByPrimaryKeySelective(record) <= 0){
            return ResultVo.error();
      }
        return ResultVo.ok();
    }

    /**
     * 旅游编号管理
     * @param model
     * @return
     */
    @RequiresPermissions("localLife:manage:tourNumber")
    @GetMapping("/tourNumber")
    public String tourNumber(Model model) {
        ListMemberParams listMemberParams = new ListMemberParams();
        if (getUserCentreId() != null) {
            listMemberParams.setCentreId(getUserCentreId());
            model.addAttribute("flag","1");
        }else {
            model.addAttribute("flag","0");
        }
        List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
        model.addAttribute("teams", teams);

        Long teamId = getUserTeamId();
        if (null != teamId) {
            model.addAttribute("teamId", teamId);
            model.addAttribute("liansuoid", teamId);
        }
        return prefix + "/tourNumber";
    }

    /**
     * 旅游编号管理列表数据
     */
    @ResponseBody
    @RequiresPermissions("localLife:manage:tourNumber")
    @GetMapping("/tourNumberList")
    public PageUtils<TourNumber> tourNumberlist(Long centreId, Long teamId, Integer status, Integer offset, Integer limit) {
        return tourNumberService.tourNumberlist( centreId, teamId,  status,  offset,  limit);
    }

    /**
     * 删除旅游编号
     */
    @ResponseBody
    @RequiresPermissions("localLife:manage:tourNumber")
    @PostMapping("/removeTourNumberList")
    public ResultVo removeTourNumberList(Long id) {
        if (id == null) {
            return ResultVo.error();
        }
        if (tourNumberService.remove(id) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    @PostMapping("/inportTourNumberExcel")
    @ResponseBody
    public ResultVo inportTourNumberExcel(@RequestParam("file") MultipartFile file) throws Exception {
        Long teamIdUser = getUserTeamId();
        if (teamIdUser != null) {
            return ResultVo.error("该权限属于平台和商户，您无权操作");
        }
        String name = file.getOriginalFilename();
        if (StringUtils.isEmpty(name)) {
            return ResultVo.error();
        }
        if (!name.endsWith("xls") && !name.endsWith("xlsx")) {
            return ResultVo.error();
        }
        InputStream inputStream = file.getInputStream();
        XSSFWorkbook wb = new XSSFWorkbook(inputStream);
        XSSFSheet sheetAt = wb.getSheetAt(0);
        try {
            for (Row row : sheetAt) {
                if (row.getRowNum() == 0) {
                    continue;
                }
                if (StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
                    return ResultVo.ok();
                }
                String code;                 //序列编码
                String password;                 //序列编码
                try {
                    code = row.getCell(0).getStringCellValue();
                    if (ValidateUtil.isEmptyObjectOrString(code)){
                        return ResultVo.error("编码不能为空!");
                    }

                    password = row.getCell(1).getStringCellValue();
                } catch (Exception e) {
                    logger.info("读取excel数据错误:{}", e.getMessage());
                    continue;
                }
                //赋值
                TourNumber tourNumber = new TourNumber();

                tourNumber.setCode(code);

                if (ValidateUtil.isNotEmptyObjectOrString(password)){
                    tourNumber.setPassword(password);
                }

                if (ValidateUtil.isNotEmptyObjectOrString(getUserCentreId())) {
                    tourNumber.setCentreId(getUserCentreId());
                }
                if (ValidateUtil.isNotEmptyObjectOrString(getUserTeamId())) {
                    tourNumber.setTeamId(getUserTeamId());
                }

                tourNumber.setStatus(0);

                int num = tourNumberMapper.insertSelective(tourNumber);
                if (num < 1) {
                    return ResultVo.error("第" + row.getRowNum() + "条数据导入失败!");
                }

            }
        } catch (Exception e) {
            logger.error("旅游编码导入失败，the message is {}", e.getMessage());
            return ResultVo.error();
        } finally {
            inputStream.close();
            wb.close();
        }
        return ResultVo.ok();
    }
}
